# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '100119': {  # 八戒支付  alipay-wap 费率1.8（102----10000）D0 loki
        'API_KEY': '7710a3cc8d8f5123acc0b3c10e2e469b',
        'gateway': 'http://www.paybajie.com/payapi/AlipayToCardGateWay.aspx',
        'query_gateway': '',
    },
    '100120': {  # 八戒支付  alipay-wap 费率1.8（102----10000）D0 witch
        'API_KEY': '989d07be4655cc9d85596da072b6496b',
        'gateway': 'http://www.paybajie.com/payapi/AlipayToCardGateWay.aspx',
        'query_gateway': '',
    },
    '100142': {  # 八戒支付  alipay-wap 费率1.6（102----10000）D0 dwc
        'API_KEY': '86f3a38977fd67579792c93d9b3ac4fb',
        'gateway': 'http://www.paybajie.com/payapi/AlipayToCardGateWay.aspx',
        'query_gateway': '',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_sign(d, key):
    s = 'MerchantNum={}&PayType={}&Amount={}&NotifyUrl={}&RequestTime={}&Key={}'.format(d['MerchantNum'], d['PayType'],
                                                                                        d['Amount'], d['NotifyUrl'],
                                                                                        d['RequestTime'], key)
    return _gen_sign(s)


def generate_notify_sign(d, key):
    s = 'MerchantOrderNum={}&Result={}&Amount={}&SystemOrderNum={}&FinishRechargeTime={}&Key={}'.format(
        d['MerchantOrderNum'], d['Result'],
        d['Amount'], d['SystemOrderNum'],
        d['FinishRechargeTime'], key)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['Sign']
    params.pop('Sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("bajiepay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        return '0'
    elif service == 'alipay_scan':
        return '1'
    return '0'


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('MerchantNum', app_id),
        ('PayType', _get_pay_type(service)),
        ('Amount', '%.2f' % pay_amount),
        ('OrderId', str(pay.id)),
        ('NotifyUrl', '{}/pay/api/{}/bajiepay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('RequestTime', local_now().strftime('%Y-%m-%d %H:%M:%S')),
        ('SyncUrl', '{}/pay/api/{}/bajiepay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),

    ))
    parameter_dict['Sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("bajiepay create: %s, order_id is:%s ", json.dumps(parameter_dict), parameter_dict['OrderId'])
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    _LOGGER.info('bajiepay url: %s', settings.PAY_CACHE_URL + cache_id)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("bajiepay notify data: %s, order_id is: %s", data, data['MerchantOrderNum'])
    verify_notify_sign(data, api_key)
    pay_id = data['MerchantOrderNum']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('bajiepay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['Result'])
    trade_no = data['SystemOrderNum']
    total_fee = float(data['Amount'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '1' and total_fee > 0.0:
        _LOGGER.info('bajiepay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pass
